package ltd.bugs.tool.signature.factory.impl;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Map;

import ltd.bugs.tool.signature.attribute.SignatureAttribute;
import ltd.bugs.tool.signature.factory.Signature;
import ltd.bugs.tool.signature.utils.ExtraUtils;
import ltd.bugs.tool.signature.utils.StringUtils;

/**
 * @author zhengzhq
 * @Title: PersonalGeneralSignature
 * @Description: 个人通用签章实现，按xxx印的方式排版
 * @date 018/8/9下午5:30
 */
public class PersonalGeneralSignature implements Signature {

  public BufferedImage draw(Font font, Color color, int width, int height,
                            Map<String, Object> extras) {
    String name = ExtraUtils.getAttributeValue(extras, SignatureAttribute.SIGNATURE_TEXT,
            String.class);
    if (StringUtils.isEmpty(name)) {
      throw new IllegalArgumentException("name can't be empty!");
    }

    int nameWidth = (name != null ? Math.max(2, name.length()) : 2) * font.getSize() + 24;
    int borderFix = ExtraUtils.getAttributeValue(extras, SignatureAttribute.BORDER_FIX,
            Integer.class, 5);
    int borderUpDown = ExtraUtils.getAttributeValue(extras, SignatureAttribute.BORDER_UP_DOWN,
            Integer.class, 3);
    int borderLeftRight = ExtraUtils.getAttributeValue(extras, SignatureAttribute.BORDER_LEFT_RIGHT,
            Integer.class, 1);
    Color borderColor = ExtraUtils.getAttributeValue(extras, SignatureAttribute.BORDER_COLOR,
            Color.class, Color.RED);

    BufferedImage image = new BufferedImage(nameWidth + borderFix * 2,
            height + borderFix * 2, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    g2d.translate(borderFix, borderFix);
    g2d.translate(nameWidth / 2, height / 2);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Stroke stroke = g2d.getStroke();
    g2d.setColor(borderColor);
    g2d.setStroke(new BasicStroke(borderUpDown));
    int x = -nameWidth / 2, y = -height / 2;
    g2d.drawLine(x, y, -x, y);
    g2d.drawLine(x, -y, -x, -y);
    g2d.setStroke(new BasicStroke(borderLeftRight));
    x -= borderLeftRight;//调整x轴封闭方框
    g2d.drawLine(x, y, x, -y);
    g2d.drawLine(-x, y, -x, -y);
    g2d.setStroke(stroke);
    if (name != null && name.length() > 0) {//绘制姓名
      g2d.setFont(font);
      g2d.setColor(color);
      FontMetrics fm = g2d.getFontMetrics();
      int w = fm.stringWidth(name);// 名称宽度
      int h = fm.getHeight();// 名称高度
      g2d.drawString(name, -w / 2, fm.getAscent() - h / 2);
    }

    return image;
  }
}
